<?php
namespace App\Http\Controllers\Front;

use Illuminate\Http\Request;
require_once __DIR__.'/../../../../app/Utilitys/Alipay/aop/AopClient.php';
require_once __DIR__.'/../../../../app/Utilitys/Alipay/aop/request/AlipayTradePagePayRequest.php';
require_once __DIR__.'/../../../../app/Utilitys/Alipay/aop/request/AlipayTradeAppPayRequest.php';
require_once __DIR__.'/../../../../app/Utilitys/Alipay/aop/request/AlipayTradeRefundRequest.php';
require_once __DIR__.'/../../../../app/Utilitys/Alipay/aop/request/AlipayTradeQueryRequest.php';
require_once __DIR__.'/../../../../app/Utilitys/Alipay/aop/request/AlipayTradeFastpayRefundQueryRequest.php';
use App\Service\Front\PayService;

class PayZfbController extends BaseController
{
    //支付

    //必须的参数
    protected $app_id = '2021004194624726';
    protected $rsaPrivateKeyFilePath = '';
    protected $rsaPrivateKey = 'MIIEowIBAAKCAQEAnLgv5fv2ernleOuSR2val8nmWWp42XPZrD9HNpgR/rDy7D/u2QDXzEbKyNZhe26vTo7uxC9vVczRD5iwBCGXLdrCSFPZdbtuqHH0MTb6WEVE3hhPWZ89WMN5TiQwtMjdBLBeNgXC2JyP6uxAItQgpQnPjwcVua5UsUNG2P89/g6YISfrYBpYZVF57ennlePPwhHYnYlTrdRlPP39JOEiz5YfBIlm3ZTFMSfSgHQKWVipJuR+/zhKb53msmZqs18RNpGm3TEedfgQYMOd6z5Ybl6s1oEd9o5n2VDzRrLXKrA7dKrEKjeEGztZNXV6LvShU2kq+j1/mauuaS7XBLAW/QIDAQABAoIBABz5IEHQdxzxSS81vfFeSydMuD1HpdftxwxFFpFNQ+ZmKELs/uc3dK3bWJoQqCz9pYNMgW/bpSWjm/LaM5BP9XcQvmJIvic545dYmeCPXXD8PWMh82mKOvkyCjccEbUafWHkiUZLgl4xc5nm22SU+wQH8Ets7+NIC3hKC8sKRRe2p7RBj6yv7M1OdUUm+a7hbyE95YSLxLqTqoVUtp4YRdUxJQin4M22PZwO9f700HGTIQ8Jty6XCL6gN7AzRslhvFFQRtrh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KcdV4JxuH7Magq2aQu5Qhfn+xJt6EkcLlQMpV4daKOdnriIicpVnsQuNiNt2TNskGxgvlTUO10s1qf6Gj/q6eu+Y2/DbhnyJPsHaqfmpqHnaOVi3jqDBHEe/7xsBZEEPETWmqgH9I6/BEUcMGDnPD/B3y0tbGCkZNi+TZVBnmW9cVrWTgVy6J4CwXKGkTapdREw0exozHnmgOsL7KuOaqBE8NDanFiHtMwuXyv6RIqJ6Yb5KkWkFSXgJalmL4ddEaIHz0mTiI3Bcp/i/Co+wIDAQAB';
    protected $alipayrsaPublicKey = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnLgv5fv2ernleOuSR2val8nmWWp42XPZrD9HNpgR/rDy7D/u2QDXzEbKyNZhe26vTo7uxC9vVczRD5iwBCGXLdrCSFPZdbtuqHH0MTb6WEVE3hhPWZ89WMN5TiQwtMjdBLBeNgXC2JyP6uxAItQgpQnPjwcVua5UsUNG2P89/g6YISfrYBpYZVF57ennlePPwhHYnYlTrdRlPP39JOEiz5YfBIlm3ZTFMSfSgHQKWVipJuR+/zhKb53msmZqs18RNpGm3TEedfgQYMOd6z5Ybl6s1oEd9o5n2VDzRrLXKrA7dKrEKjeEGztZNXV6LvShU2kq+j1/mauuaS7XBLAW/QIDAQAB';
    protected $notify_url = ''; //通知接口

    public function __construct()
    {
        $this->rsaPrivateKeyFilePath = 'zfb/rsaPrivateKeyFilePath.txt';
        $this->notify_url = env('DOMAIN') . '/api/front/pay/zfb/notice';
        $this->db = new PayService();
    }

    //测试
    public function test(){
        $aop = new \AopClient();
        $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
        $aop->appId = $this->app_id;
        $aop->rsaPrivateKey = $this->rsaPrivateKey;
        $aop->alipayrsaPublicKey = $this->alipayrsaPublicKey;
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset = 'utf-8';
        $aop->format = 'json';
        $reqObj = new \AlipayTradePagePayRequest();
        $reqObj->setBizContent(json_encode([
            'out_trade_no' => (string) time(),
            'total_amount' => '0.01',
            'subject' => 'order',
            'product_code' => 'FAST_INSTANT_TRADE_PAY',
        ], JSON_UNESCAPED_UNICODE));
        $aop->sdkExecute($reqObj);
        return $this->toJson();
    }

    //接入支付
    public function pay(Request $request)
    {
        $token = $request->post('token', ''); //登录token
        $type = $request->post('type', 1); //1原创需求订单
        $orderno = $request->post('orderno', 0); //订单号
        $orderOne = $this->db->orderOne($type, $orderno);
        if ($orderOne['code'] < 0) {
            return $this->toJson(-2, '订单错误');
        }
        $price = toNumber($orderOne['data']['price']);
        $xqtitle = $orderOne['data']['title'];
        $uOne = $this->db->userByToken($token);
        if (!$uOne) {
            return $this->toJson(-2, '未登录');
        }
        $aop = new \AopClient();
        $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
        $aop->appId = $this->app_id;
        $aop->rsaPrivateKey = $this->rsaPrivateKey;
        $aop->alipayrsaPublicKey = $this->alipayrsaPublicKey;
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset = 'utf-8';
        $aop->format = 'json';
        $payData = [
            'uid' => $uOne['id'],
            'out_trade_no' => $orderno,
            'money' => $price * 100,
            'order_sign' => json_encode($aop, JSON_UNESCAPED_UNICODE)
        ];
        $lastid = $this->db->zfbPayAdd($payData);
        $reqObj = new \AlipayTradePagePayRequest();
        $reqData = json_encode([
            'body' => 'order',
            'out_trade_no' => (string) $orderno,
            'total_amount' => $price,
            'subject' => '原创案例需求订单-'.$xqtitle,
            'product_code' => 'FAST_INSTANT_TRADE_PAY',
        ], JSON_UNESCAPED_UNICODE);
        $reqObj->setNotifyUrl($this->notify_url);
        $reqObj->setBizContent($reqData);
        $this->db->zfbPayModify($lastid, ['order_req' => $reqData]);
        $res = $aop->pageExecute($reqObj, 'GET');
        $responseNode = str_replace(".", "_", $reqObj->getApiMethodName()) . "_response";
        $backData = json_encode([
            'response' => $responseNode,
            'url' => $res,
        ], JSON_UNESCAPED_UNICODE);
        $this->db->zfbPayModify($lastid, ['order_back' => $backData]);
        return $this->toJson(0, '', ['alipayUrl' => $res]);
    }

    //异步支付通知
    public function notice(Request $request)
    {
        $zfb = $request->all();
        $lastid = $this->db->zfbNotice($zfb);
//        if (!$lastid) {
//            return $this->toJson(-1, 'error');
//        }
        return $this->toJson();
    }

    //同步查询支付状态
    public function query(Request $request)
    {
        $orderno = $request->post('orderno', '');
        $aop = new \AopClient();
        $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
        $aop->appId = $this->app_id;
        $aop->rsaPrivateKey = $this->rsaPrivateKey;
        $aop->alipayrsaPublicKey = $this->alipayrsaPublicKey;
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset = 'utf-8';
        $aop->format = 'json';
        $reqObj = new \AlipayTradeQueryRequest();
        // 设置订单支付时传入的商户订单号
        $reqObj->setBizContent(json_encode([
            'out_trade_no' => $orderno,
        ], JSON_UNESCAPED_UNICODE));
        // 如果是第三方代调用模式，请设置app_auth_token（应用授权令牌）
        $rst = $aop->execute($reqObj, 0, 0, 0, 1);
        $lastid = $this->db->zfbNotice($rst);
        if ($rst['code'] != 10000) {
            return array('code' => $rst['code'], 'msg' => $rst['msg'], 'zfbdata' => $rst);
        }
        if ($rst['trade_status'] != 'TRADE_SUCCESS') {
            return array('code' => $rst['code'], 'msg' => $rst['TRADE_SUCCESS'], 'zfbdata' => $rst);
        }
        //更新订单状态
        $this->db->zfbNoticeModify($lastid, $orderno);
        return $this->toJson();
//        var_dump($rst);
//        //ddd($aop, $reqObj, $responseResult);
//        $responseApiName = str_replace(".","_",$reqObj->getApiMethodName())."_response";
//        $response = $responseResult->$responseApiName;
//        if(!empty($response->code)&&$response->code==10000){
//            echo("调用成功");
//        }
//        else{
//            echo("调用失败");
//        }
    }

    //退款
    public function refund(Request $request)
    {
        $orderno = $request->post('orderno', '');
        $price = $request->post('price', 0.01);
        $aop = new \AopClient();
        $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
        $aop->appId = $this->app_id;
        $aop->rsaPrivateKey = $this->rsaPrivateKey;
        $aop->alipayrsaPublicKey = $this->alipayrsaPublicKey;
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset = 'utf-8';
        $aop->format = 'json';
        $reqObj = new \AlipayTradeRefundRequest();
        $reqData = json_encode([
            'out_trade_no' => (string) $orderno,
            'refund_amount' => $price,
        ], JSON_UNESCAPED_UNICODE);
//        var_dump($reqData); echo '<br><br>';
        $reqObj->setBizContent($reqData);
//        var_dump($reqObj); echo '<br><br>';
        $rst = $aop->execute($reqObj, 1);
        if (!$rst) {
            return $this->toJson(-2, 'ali error');
        }
        $rst = json_decode(json_encode($rst), true);
        if (!isset($rst['alipay_trade_refund_response'])) {
            return $this->toJson(-2, 'response error');
        }
        $rst = $rst['alipay_trade_refund_response'];
        if ($rst['code'] != 10000) {
            return $this->toJson(-2, $rst['msg'], $rst);
        }
//        var_dump($rst);
        return $this->toJson(0, '', $rst);

//        $responseApiName = str_replace(".","_",$reqObj->getApiMethodName())."_response";
//        $response = $responseResult->$responseApiName;
//        if(!empty($response->code)&&$response->code==10000){
//            echo("调用成功");
//        }
//        else{
//            echo("调用失败");
//        }
    }

    //同步查询退款状态
    public function refundQuery(Request $request)
    {
        $orderno = $request->post('orderno', '');
        $aop = new \AopClient();
        $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
        $aop->appId = $this->app_id;
        $aop->rsaPrivateKey = $this->rsaPrivateKey;
        $aop->alipayrsaPublicKey = $this->alipayrsaPublicKey;
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset = 'utf-8';
        $aop->format = 'json';
        $reqObj = new \AlipayTradeFastpayRefundQueryRequest();
        $reqData = json_encode([
            'out_request_no' => (string) $orderno,
            'out_trade_no' => (string) $orderno,
        ], JSON_UNESCAPED_UNICODE);
//        var_dump($reqData); echo '<br><br>';
        $reqObj->setBizContent($reqData);
//        var_dump($reqObj); echo '<br><br>';
        $rst = $aop->execute($reqObj, 1);
//        ddd($rst);
        $rst = json_decode(json_encode($rst), true);
        if (!isset($rst['alipay_trade_fastpay_refund_query_response'])) {
            return $this->toJson(-2, 'response error');
        }
        $rst = $rst['alipay_trade_fastpay_refund_query_response'];
        if ($rst['code'] != 10000) {
            return $this->toJson(-2, $rst['msg'], $rst);
        }
//        var_dump($rst);
        return $this->toJson(0, '', $rst);
    }
}